package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/zw2582/zm_go_lib/helpers"
	"time"
)

type User struct {
	Id uint `json:"id" orm:"auto;pk"`
	UUID string `json:"uuid" orm:"column(uuid)" description:"唯一id"`
	Name string `json:"name" description:"用户名称"`
	Avatar string `json:"avatar" description:"用户头像"`
	Gender uint `json:"gender" description:"1.男 2.女 3.未知"`
	Types uint `json:"type" description:"类型 1.顾客 2.客服"`
	CreatedAt time.Time `json:"created_at" orm:"auto_now_add;type(datetime)"`
	UpdatedAt time.Time `json:"updated_at" orm:"auto_now;type(datetime)"`
	Status uint `json:"status"`
}

func init()  {
	orm.RegisterModel(new(User))
}

//UserCreate 获取或新增用户
func UserCreate(uuid, name, avatar string, gender, types uint) (u User, err error) {
	if uuid == "" {
		return u, fmt.Errorf("缺少uuid")
	}
	if name == "" {
		return u, fmt.Errorf("缺少姓名")
	}
	if helpers.IndexOf([]uint{1,2}, types) == -1 {
		return u, fmt.Errorf("类型错误 1.顾客 2.客服")
	}
	//查询是否存在
	o := orm.NewOrm()
	err = o.QueryTable(User{}).Filter("uuid", uuid).Filter("types", types).Filter("status", 1).One(&u)
	if err != nil && err != orm.ErrNoRows {
		panic(err)
	}

	if u.UUID == "" {
		u.UUID = uuid
	}
	if name != "" && u.Name != name {
		u.Name = name
	}
	if avatar != "" && u.Avatar != avatar {
		u.Avatar = avatar
	}
	if u.Gender == 0 {
		u.Gender = gender
	}
	if u.Types == 0 {
		u.Types = types
	}
	u.Status = 1
	if u.Id == 0 {
		//没有查到则新增
		i, err := o.Insert(&u)
		if err != nil {
			panic(err)
		}
		u.Id = uint(i)
	} else {
		//查到则修改
		_,err = o.Update(&u)
		if err != nil {
			panic(err)
		}
	}
	return u, nil
}

func UserGet(uid uint) (u User) {
	o := orm.NewOrm()

	o.QueryTable(User{}).Filter("id", uid).One(&u)
	return
}

func UserGetByUuid(uuid string) (u User) {
	o := orm.NewOrm()

	o.QueryTable(User{}).Filter("uuid", uuid).One(&u)
	return
}

//根据userid列表查询用户信息
func UserListInId(uid []interface{}) (results []User) {
	o := orm.NewOrm()
	_, err := o.QueryTable(User{}).Filter("id__in", uid...).All(&results)
	if err != nil && err != orm.ErrNoRows {
		panic(err)
	}
	return
}